04. Database Migrations

DB Migrations for Heroku

Database Manage & Migrations on Heroku

In the data modeling course, you learned how to use migrations to manage your database schema and changes that you make to it. Heroku can run all your migrations to the database you have hosted on the platform, but in order to do so, your application needs to include a manage.py file.

We'll need three new packages in the file. Run the following commands to install them:

pip install flask_script
pip install flask_migrate
pip install psycopg2-binary

The manage.py file will contain the following code:

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

from app import app
from models import db

migrate = Migrate(app, db)
manager = Manager(app)

manager.add_command('db', MigrateCommand)


if __name__ == '__main__':
    manager.run()

Now we can run our local migrations using our manage.py file, to mirror how Heroku will run behind the scenes for us when we deploy our application:

python manage.py db init
python manage.py db migrate
python manage.py db upgrade

Those last commands are the essential process that Heroku will run to ensure your database is architected properly. We, however, won't need to run them again unless we're testing the app locally.

REMINDER: Because you installed new packages you need to use freeze again to update the requirements.txt file.

Before moving forward, make sure that your file structure matches that above if you’re working on the sample project.

Before moving forward, make sure that your file structure matches that above if you’re working on the sample project.